package cn.pconline.autoclub.web.app;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaPraise;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserForum;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.UserForumService;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.web.UserAuth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2015年5月8日 下午3:36:39
 */
@Controller
@RequestMapping(value = "/appapi")
public class AppUserForumController {

	@Autowired
	private UserForumService userForumService;
	@Autowired
	private UserAuth userAuth;
	@Autowired
	private DynaService dynaService;
	@Autowired
        private IntfService intfService;
	//车友圈名字长度
	private static final int FORUMNAME_LEN_255 = 255;
        /**
         * 论坛版块状态标识 1:有效，0：无效
         */
	private static final int FORUM_STATUS_FAIL = 0;
        /**
         * 论坛版块状态标识
         */
        private static final int FORUM_STATUS_NORMAL = 1; 
	/**
	 * 绑定车友圈
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/1.0/forum/bundUserForum.do", method = RequestMethod.POST)
	public void BundUserForum(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		long forumId = WebUtils.paramLong(request, "forumId", 0L);
		String callback = AppControllerStatic.paramCallback(request);
		JSONObject jsonObject = new JSONObject();
		if(forumId <= 0 ) {
			AppControllerStatic.printErrorMsg(response, "车友圈信息错误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
                Long[] ids = new Long[]{forumId};
		JSONArray array = intfService.getForumByForumIds(ids);
                if(array == null || array.size() == 0){
                    AppControllerStatic.printErrorMsg(response, "车友圈信息错误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
                JSONObject forumObj = array.getJSONObject(0);
                if(forumObj == null || forumObj.getIntValue("isValid")==FORUM_STATUS_FAIL){
                    AppControllerStatic.printErrorMsg(response, "车友圈信息错误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
                String forumName = forumObj.getString("forumName");
		//是否登录
		User user = userAuth.getUser(request, response);
		if(user.getUid() <= 0){
			AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		long userId = user.getUid();
		//是否已经绑定
		UserForum userForum = userForumService.findByUserIdFourmId(userId, forumId);
		if(userForum == null) {//新绑定
			UserForum newUserForum = new UserForum();
			newUserForum.setUserId(userId);
			newUserForum.setForumId(forumId);
			newUserForum.setForumName(forumName);
			newUserForum.setStatus(UserForum.STATUS_NORMAL);
			Date date = new Date();
			newUserForum.setCreateDate(date);
			newUserForum.setUpdateDate(date);
			userForumService.create(newUserForum);
		} else if(userForum.getStatus() == UserForum.STATUS_DELETE){//重新绑定
			Date date = new Date();
			userForum.setCreateDate(date);
			userForum.setUpdateDate(date);
			userForum.setForumName(forumName);
			userForumService.active(userForum);
		} else if(userForum.getStatus() == UserForum.STATUS_NORMAL){//已经绑定过
			AppControllerStatic.printErrorMsg(response, "不能重复绑定", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);;
			return;
		}
		AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 解绑车友圈
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/1.0/forum/unBundUserForum.do", method = RequestMethod.POST)
	public void UnBundUserForum(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		long forumId = WebUtils.paramLong(request, "forumId", 0L);
		String callback = AppControllerStatic.paramCallback(request);
		JSONObject jsonObject = new JSONObject();
		
		//是否登录
		User user = userAuth.getUser(request, response);
		if(user.getUid() <= 0){
			AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		
		long userId = user.getUid();
		
		//是否已经绑定
		UserForum userForum = userForumService.findByUserIdFourmId(userId, forumId);
		if(userForum == null) {
			AppControllerStatic.printErrorMsg(response, "该车友圈不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		
		if(userForum.getStatus() != UserForum.STATUS_DELETE) {
			userForum.setUpdateDate(new Date());
			userForumService.deActive(userForum);
		}
		
		AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 根据用户ID，获取绑定车友圈列表
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/1.0/forum/listForumsByUserId.do", method = RequestMethod.GET)
	public void listForumsByUserId(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		String callback = AppControllerStatic.paramCallback(request);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		
		//是否登录
		User user = userAuth.getUser(request, response);
		if(user.getUid() <= 0){
			AppControllerStatic.printLoginErrorMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		
		long userId = user.getUid();
		
		//是否已经绑定
		List<UserForum> list = userForumService.listByUserIdStatus(userId, UserForum.STATUS_NORMAL);
		for(UserForum userForum : list) {
			JSONObject json =  new JSONObject();
			json.put("forumId", userForum.getForumId());
			json.put("forumName", userForum.getForumName());
			
			jsonArray.add(json);
		}
		
		jsonObject.put("forumList", jsonArray);
		jsonObject.put("userId", userId);
		
		AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 判断是否已绑定此车友圈
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/1.0/forum/isBound.do", method = RequestMethod.GET)
	public void isBound(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		String callback = AppControllerStatic.paramCallback(request);
		long userId = AppControllerStatic.paramUserId(request);
		long forumId = WebUtils.paramLong(request, "forumId", 0L);
		
		JSONObject jsonObject = new JSONObject();

		UserForum userForum = userForumService.findByUserIdFourmId(userId, forumId);
		if(userForum == null || userForum.getStatus() != UserForum.STATUS_NORMAL) {
			jsonObject.put("isBound", 0);
		}else{
			jsonObject.put("isBound", 1);
		}
		
		jsonObject.put("userId", userId);
		jsonObject.put("forumId", forumId);
		
		AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 根据帖子ID，帖子创建时间，获取对应的车友会动态
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/1.0/forum/getDynaByTopicId.do", method = RequestMethod.GET)
	public void getDynaByTopicId(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		String callback = AppControllerStatic.paramCallback(request);
		long topicId = WebUtils.paramLong(request, "topicId", 0L);
		long userId = AppControllerStatic.paramUserId(request);
		Date createDate = WebUtils.parseDate(request, "createDate");
		
		JSONObject jsonObject = new JSONObject();
		
		if(topicId <=0 || createDate == null) {
			AppControllerStatic.printErrorMsg(response, "主题信息有误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		
		//获取动态信息
		DynaInfo dynaInfo = dynaService.findDynaInfoByTopicId(topicId, createDate);
		if(dynaInfo == null) {
			AppControllerStatic.printErrorMsg(response, "找不到匹配的动态", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		} 
		long dynaInfoId = dynaInfo.getDynaInfoId();
		
		//判断用户是否已经过此动态
		DynaPraise dynaPraise = dynaService.findDynaPraise(userId, dynaInfoId);
		if(dynaPraise != null) {
			jsonObject.put("isPraise", dynaPraise.getStatus());
		} else {
			jsonObject.put("isPraise", DynaPraise.STATUS_UNPRAISE);
		}
		
		jsonObject.put("dynaInfoId", dynaInfoId);
		jsonObject.put("praiseCount", dynaInfo.getPraiseCount());
		jsonObject.put("postCount", dynaInfo.getPostCount());
		jsonObject.put("topicId", topicId);
		jsonObject.put("createDate", createDate);
		jsonObject.put("appTitle", dynaInfo.getAppTitle());
		jsonObject.put("title", dynaInfo.getTitle());
		
		AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
}
